<template>
  <div>
    <van-search v-model="searchText" show-action shape="round" placeholder="请输入名称或代码查询单品种状态"
                @focus="resultShow = true"
                @search="onSearch" @cancel="onCancel">
      <template #action>
        <div style="color: #1989fa;" @click="onSearch">查询</div>
      </template>
    </van-search>
    <van-cell-group v-show="resultShow">
      <van-cell v-for="(item, index) in resultList" is-link :key="index" :title="item.title"
                :value="item.symbol" @click="onSubmit(item)">
        <template #title>
          <van-tag type="primary" v-if="Object.hasOwnProperty.call(item, 'sequence')">
            <span v-if="item.sequence">次{{ item.sequence > 9 ? item.sequence : `0${item.sequence}` }}</span>
            <span v-else>主力</span>
          </van-tag>
          <van-tag type="primary">{{ getOptionsTarget($types.sectorTypes, 'value', item.sector, 'text') }}</van-tag>
          <span>{{ item.title }}</span>
        </template>
      </van-cell>
    </van-cell-group>
  </div>
</template>

<script>
import {getOptionsTarget} from '@/utils'

export default {
  props: {
    url: String,
    sectorList: {
      type: Array,
      default: () => ([])
    }
  },
  data() {
    return {
      resultShow: false,
      searchText: null,
      resultList: [],
      symbolList: [],
    }
  },
  methods: {
    getOptionsTarget: getOptionsTarget,
    onSearch() {
      this.resultList = this.symbolList.filter(item => {
        if (item.words.search(this.searchText) > -1) {
          if (this.sectorList.length > 0) {
            return this.sectorList.indexOf(item.sector) > -1
          } else {
            return true
          }
        } else {
          return false
        }
      }).slice(0, 100)
    },
    onCancel() {
      this.searchText = null
      this.resultList = []
    },
    onSubmit(item) {
      this.searchText = null
      this.resultShow = false
      this.$emit('confirm', item)
    },
    onInit() {
      this.$requests.post(this.url).then(resp => {
        this.symbolList = resp.map(item => {
          let temp = {
            sector: item.sector,
            market: item.market,
            symbol: item.symbol,
            title: item.title
          }
          temp = Object.assign({words: Object.values(temp).join()}, temp)
          if(Object.hasOwnProperty.call(item, 'sequence')) {
            temp.sequence = item.sequence
          }
          return temp
        })
      })
    }
  },
  mounted() {
    this.onInit()
  }
}
</script>
